package com.hillstone.oauth2server.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.token.TokenService;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;

import java.lang.reflect.Field;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @anthor: lddd
 * @date: 2022/4/17 - 1:21
 * @description:
 **/
public class TokenUtil {
    @Autowired
    private TokenStore tokenStore;
    /**
     * 根据token获取用户名
     *
     *<hr>
     * @author hanjidong
     * @date 2020年12月16日 上午10:37:12
     * @since 0.0.1
     * @param access_token
     * @return
     * String
     */
    public Object getUserNameByToken(String access_token) {
        try {
            OAuth2AccessToken readAccessToken = tokenStore.readAccessToken(access_token);
            if(readAccessToken == null){
                throw new IllegalArgumentException("token无效");
            }
            if(readAccessToken.isExpired()){
                throw new RuntimeException("token已过期");
            }
            OAuth2Authentication oAuth2Authentication = null;
            Field authenticationStore = tokenStore.getClass().getDeclaredField("authenticationStore");
            authenticationStore.setAccessible(true);
            Object authenticationStoreObj = authenticationStore.get(tokenStore);
            if (authenticationStoreObj instanceof ConcurrentHashMap) {
                ConcurrentHashMap<String, OAuth2Authentication> nticationStoreObjMap = (ConcurrentHashMap<String, OAuth2Authentication>) authenticationStoreObj;
                oAuth2Authentication = nticationStoreObjMap.get(access_token);
            }
            Object principal = oAuth2Authentication.getPrincipal();
            return principal;
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }
}